<?php
// +----------------------------------------------------------------------
// | HisiPHP框架[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2021 http://www.hisiphp.com
// +----------------------------------------------------------------------
// | HisiPHP承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 橘子俊 <364666827@qq.com>，开发者QQ群：50304283
// +----------------------------------------------------------------------

namespace app\system\admin;

use app\common\service\Factory;
use app\system\model\SystemUser as UserModel;
use app\system\model\SystemRole as RoleModel;
use app\system\model\SystemMenu as MenuModel;
use hisi\Tree;
use app\common\service\Factory as FactoryService;
use GatewayClient\Gateway;
use app\common\service\User as UserService;

/**
 * 后台用户、角色控制器
 * @package app\system\admin
 */
class UserV2 extends Admin
{
    public $tabData = [];
    protected $hisiTable = 'SystemUser';
    protected $hisiModel = 'SystemUser';
    /**
     * @var \app\common\service\Factory
     */
    protected $factoryServer;

    /**
     * 初始化方法
     */
    protected function initialize()
    {
        parent::initialize();

        $tabData['menu'] = [
            [
                'title' => '管理角色',
                'url' => 'system/userV2/role',
            ],
            [
                'title' => '管理员',
                'url' => 'system/userV2/index',
            ],
        ];
        $this->tabData = $tabData;
    }

    /**
     * 用户管理
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function index($q = '')
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 15);
            $keyword = $this->request->param('keyword/s', '');
            $roleId = $this->request->param('role_id/d', 0);
            $where[] = ['id', 'neq', 1];
            if ($keyword) {
                $where[] = ['username|nick', 'like', "%{$keyword}%"];
            }
            if ($roleId) {
                $where[] = ['id', 'in', db('system_user_role')->where('role_id', $roleId)->column('user_id')];
            }

            Gateway::$registerAddress = env('register_address');
            try {
                $allUidOnlineList = Gateway::getAllUidList();
            } catch (\Exception $e) {
                $allUidOnlineList = [];
            }

            $data['data'] = UserModel::with('hasRoles')->where($where)->page($page)->limit($limit)->select();
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['is_online'] = in_array($v['id'], $allUidOnlineList) ? 1 : 0;
            }

            $data['count'] = UserModel::where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $assign = [];
        $assign['hisiTabData'] = $this->tabData;
        $assign['hisiTabType'] = 3;
        $assign['factoryKV'] = json_encode(getFactoryKV(true));
        $assign['rolesKV'] = ['0' => '请选择'] + RoleModel::where('id', '>', IS_ROOT ? 0 : 1)->order('id asc')->column('name', 'id');

        return $this->assign($assign)->fetch();
    }

    /**
     * 布局切换
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function iframe()
    {
        $val = UserModel::where('id', ADMIN_ID)->value('iframe');
        if ($val == 1) {
            $val = 0;
        } else {
            $val = 1;
        }
        if (!UserModel::where('id', ADMIN_ID)->setField('iframe', $val)) {
            return $this->error('切换失败');
        }
        cookie('hisi_iframe', $val);
        return $this->success('请稍等，页面切换中...', url('system/index/index'));
    }

    /**
     * 主题设置
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function setTheme()
    {
        $theme = $this->request->param('theme/d', 0);
        if (UserModel::setTheme($theme, true) === false) {
            return $this->error('设置失败');
        }
        return $this->success('设置成功');
    }

    /**
     * 添加用户
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function addUser()
    {
        $factoryKV = (new FactoryService())->getKVCache();
        if ($this->request->isPost()) {

            $data = $this->request->post();

            $data['password'] = md5($data['password']);
            $data['password_confirm'] = md5($data['password_confirm']);

            // 验证
            $result = $this->validate($data, 'SystemUser');
            if ($result !== true) {
                return $this->error($result);
            }

            unset($data['id'], $data['password_confirm']);

            $data['last_login_ip'] = '';
            $data['auth'] = '';
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);

            if (!isset($data['factory_ids']) || count($data['factory_ids']) == 0) {
                $data['factory_ids'] = '';
            } elseif (isset($data['factory_ids']) && count($data['factory_ids']) > 0 &&
                (in_array(0, $data['factory_ids']) || count($factoryKV) == count($data['factory_ids']))
            ) {
                $data['factory_ids'] = '*';
            } else {
                $data['factory_ids'] = implode(',', $data['factory_ids']);
            }

            if (!UserModel::create($data)) {
                return $this->error('添加失败');
            }

            return $this->success('添加成功');
        }

        $this->assign('menus', []);
        $this->assign('roles', RoleModel::where('id', '>', IS_ROOT ? 0 : 1)->order('id asc')->column('id,name'));

        // 获取工厂列表
        $this->assign('factoryKV', ['0' => '全部工厂'] + $factoryKV);
        $factory_ids_selected = [0];
        $this->factoryServer = new Factory();
        list(, $list_tree) = $this->factoryServer->getAllTree([]);
        $this->assign('menu_factory', $list_tree);
        $this->assign('factory_ids_selected', $factory_ids_selected);
        return $this->fetch('userform');
    }

    /**
     * 修改用户
     * @param int $id
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function editUser($id = 0)
    {
        if ($id == 1 || ADMIN_ID == $id) {
            return $this->error('禁止修改当前登录用户');
        }

        $factoryKV = (new FactoryService())->getKVCache();
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($data['password']) {
                $data['password'] = md5($data['password']);
                $data['password_confirm'] = md5($data['password_confirm']);
            }

            if (!isset($data['factory_ids']) || count($data['factory_ids']) == 0) {
                $data['factory_ids'] = '';
            } elseif (isset($data['factory_ids']) && count($data['factory_ids']) > 0 &&
                (in_array(0, $data['factory_ids']) || count($factoryKV) == count($data['factory_ids']))
            ) {
                $data['factory_ids'] = '*';
            } else {
                $data['factory_ids'] = implode(',', $data['factory_ids']);
            }

            // 验证
            $result = $this->validate($data, 'SystemUser.update');
            if ($result !== true) {
                return $this->error($result);
            }

            if ($data['password']) {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            } else {
                unset($data['password']);
            }

            if (!UserModel::update($data)) {
                return $this->error('修改失败');
            }
            return $this->success('修改成功');
        }

        $row = UserModel::with('hasIndexs')->where('id', '=', $id)->field('id,username,nick,email,mobile,factory_ids,sub_factory_id,tags,status')->find()->toArray();        //dump($row);

        $row['role_id'] = array_column($row['has_indexs'], 'role_id');

        // 获取工厂列表
        $this->assign('factoryKV', ['0' => '全部工厂'] + $factoryKV);
        $factory_ids_selected = [];
        if (trim($row['factory_ids']) != '') {
            $factory_ids_array = explode(',', $row['factory_ids']);
            foreach ($factory_ids_array as $k => $v) {
                if ($v == '*') {
                    $factory_ids_selected[] = 0;
                    break;
                }
                $factory_ids_selected[] = $v;
            }
        }
        $this->factoryServer = new Factory();
        list(, $list_tree) = $this->factoryServer->getAllTree([$row['sub_factory_id']]);
        $this->assign('menu_factory', $list_tree);
        $this->assign('roles', RoleModel::where('id', '>', IS_ROOT ? 0 : 1)->order('id asc')->column('id,name'));
        $this->assign('formData', $row);
        $this->assign('factory_ids_selected', $factory_ids_selected);
        return $this->fetch('userform');
    }

    /**
     * 修改个人信息
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function info()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['id'] = ADMIN_ID;
            // 防止伪造篡改
            unset($data['role_id'], $data['status']);

            if ($data['password']) {
                $data['password'] = md5($data['password']);
                $data['password_confirm'] = md5($data['password_confirm']);
            }

            // 验证
            $result = $this->validate($data, 'SystemUser.info');
            if ($result !== true) {
                return $this->error($result);
            }

            if ($data['password']) {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            } else {
                unset($data['password']);
            }

            if (!UserModel::update($data)) {
                return $this->error('修改失败');
            }
            return $this->success('修改成功');
        }

        $row = UserModel::where('id', ADMIN_ID)->field('username,nick,email,mobile')->find()->toArray();
        $this->assign('formData', $row);
        return $this->fetch();
    }

    /**
     * 删除用户
     * @param int $id
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function delUser()
    {
        parent::del();
    }

    // +----------------------------------------------------------------------
    // | 角色
    // +----------------------------------------------------------------------

    /**
     * 角色管理
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function role()
    {
        if ($this->request->isAjax()) {
            $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 15);
            $keyword = $this->request->param('keyword/s', '');

            $where = [];
            if ($keyword) {
                $where[] = ['name|intro', 'like', "%{$keyword}%"];
            }

            $data['data'] = RoleModel::where('id', '<>', 1)->where($where)->select();
            $data['count'] = RoleModel::where('id', '<>', 1)->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $this->assign('hisiTabData', $this->tabData);
        $this->assign('hisiTabType', 3);
        return $this->fetch();
    }

    /**
     * 添加角色
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function addRole()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['auth'] = explode(',', $data['auth_str']);
            unset($data['auth_str']);

            // 验证
            $result = $this->validate($data, 'SystemRole');
            if ($result !== true) {
                return $this->error($result);
            }
            unset($data['id']);
            if (!RoleModel::create($data)) {
                return $this->error('添加失败');
            }
            return $this->success('添加成功');
        }
        $tabData = [];
        $tabData['menu'] = [
            ['title' => '添加角色'],
            ['title' => '设置权限'],
        ];

        $menuList = MenuModel::getAuthTreeNew([], 0, 0);
        $this->assign('menus', $menuList);
        $this->assign('hisiTabData', $tabData);
        $this->assign('hisiTabType', 2);

        return $this->fetch('roleform');
    }

    /**
     * 修改角色
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function editRole($id = 0)
    {
        if ($id <= 1) {
            return $this->error('禁止编辑');
        }

        if ($this->request->isPost()) {
            $roles = explode(',', ADMIN_ROLE);
            if (in_array($id, $roles)) {
                return $this->error('禁止修改自身角色');
            }

            $data = $this->request->post();
            $data['auth'] = $auth = explode(',', $data['auth_str']);
            unset($data['auth_str']);

            // 验证
            $result = $this->validate($data, 'SystemRole');
            if ($result !== true) {
                return $this->error($result);
            }
            $data['auth'] = json_encode($auth);
            $data['mtime'] = time();
            if (!db('system_role')->where('id', $id)->update($data)) {
                return $this->error('修改失败');
            }
            // 更新权限缓存
            session('role_auth_' . $data['id'], $auth);
            return $this->success('修改成功');
        }
        $tabData = [];
        $tabData['menu'] = [
            ['title' => '修改角色'],
            ['title' => '设置权限'],
        ];
        $row = RoleModel::where('id', $id)->field('id,name,intro,auth,status')->find()->toArray();

        $this->assign('formData', $row);

        $menuList = MenuModel::getAuthTreeNew($row['auth'], 0, 0);
        $this->assign('menus', $menuList);

        $this->assign('hisiTabData', $tabData);
        $this->assign('hisiTabType', 2);

        return $this->fetch('roleform');
    }

    /**
     * 角色状态设置
     */
    public function statusRole()
    {
        $this->hisiModel = 'SystemRole';

        $id = $this->request->param('id/a');
        $roles = explode(',', ADMIN_ROLE);
        if (array_intersect($id, $roles)) {
            return $this->error('禁止修改自身角色状态');
        }

        parent::status();
    }

    /**
     * 删除角色
     * @param int $id
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function delRole()
    {
        $this->hisiModel = 'SystemRole';

        $id = $this->request->param('id/a');
        $roles = explode(',', ADMIN_ROLE);
        if (array_intersect($id, $roles)) {
            return $this->error('禁止删除自身角色');
        }

        parent::del();
    }

    /**
     * 设置个人权限
     * @date 9月25日
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function editAuth($id = 0)
    {
        $userService = new UserService();
        if ($id <= 1) {
            return $this->error('禁止编辑');
        }

        if ($this->request->isPost()) {
            if ($id == ADMIN_ID) {
                return $this->error('禁止修改自身个人权限');
            }

            $data = $this->request->post();//dump($data);
            $data['private_auth'] = $auth = explode(',', $data['auth_str']);
            unset($data['auth_str']);
            $data['private_auth'] = json_encode($auth);
            $data['mtime'] = time();
            if (!db('system_user')->where('id', $id)->update($data)) {
                return $this->error('修改失败');
            }

            // 更新权限缓存
            session('private_auth_' . $data['id'], $auth);
            return $this->success('修改成功');
        }
        $tabData = [];
        $tabData['menu'] = [
            ['title' => '设置权限'],
        ];
        $row = $userService->getUserPrivateAuth($id);
        $this->assign('formData', $row);
        $menuList = MenuModel::getAuthTreeNew($row['private_auth'], 0, 0);
        $this->assign('menus', $menuList);

        $this->assign('hisiTabData', $tabData);
        $this->assign('hisiTabType', 2);

        return $this->fetch('authform');
    }
}
